package com.skyon.sdk;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import com.skyon.sdk.bean.ResultBean;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
import java.util.TreeSet;
import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.LOCATION_SERVICE;
import static android.content.Context.SENSOR_SERVICE;
import static android.content.Context.WIFI_SERVICE;


public class MSUCommon {

    /**
     * 1.  设备名称
     */
    public static String model1 = Build.MODEL;

    /**
     * 2.   获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage2() {
        try {
            return Locale.getDefault().getLanguage();
        } catch (Exception e) {
            Log.e("2", e.getMessage());
            return "";
        }
    }

    /**
     * 3 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel3() {
        try {
            return Build.MODEL;

        } catch (Exception e) {
            Log.e("3", e.getMessage());
            return "";
        }
    }

    /**
     * 4 操作系统平台
     *
     * @return String
     */
    public static String getSys4() {
        return "android";
    }

    /**
     * 5 获取运营商
     *
     * @param context
     */
    public static String getSim5(Context context) {
        try {
            TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    ((Activity) context).requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
                }
            }

            String operator = telManager != null ? telManager.getSimOperator() : "";
            if (operator != null) {
                if (operator.equals("46000") || operator.equals("46002") || operator.equals("46007")) {
                    return "中国移动";
                } else if (operator.equals("46001") || operator.equals("46006")) {
                    return "中国联通";
                } else if (operator.equals("46003") || operator.equals("46011")) {
                    return "中国电信";
                }
            }
        } catch (Exception e) {
            Log.e("5", e.getMessage());
            return "";
        }
        return "";
    }

    /**
     * 6 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion6() {
        try {
            return Build.VERSION.RELEASE;

        } catch (Exception e) {
            Log.e("6", e.getMessage());
            return "";
        }
    }

    /**
     * 7 获取国家码
     */
    public static String getCountryZipCode7(Context context) {
        try {
            return getIMSI8(context).substring(0,3);
        } catch (Exception e) {
            Log.e("7", e.getMessage());
            return "460";
        }
    }

    /**
     * 7 获取网络码
     *
     * @param context
     * @return
     */
    public static String getNetworkNum7(Context context) {
        try {
            String sim = getSim5(context);
            if (sim.equals("中国移动")) {
                return "02";
            } else if (sim.equals("中国联通")) {
                return "01";
            } else if (sim.equals("中国电信")) {
                return "03";
            }
        } catch (Exception e) {
            Log.e("7", e.getMessage());
            return "";
        }
        return "";
    }

    /**
     * 8 获取手机IMSI号
     */
    public static String getIMSI8(Context context) {
        try {
            TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    ((Activity) context).requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
                }
            }
            return mTelephonyMgr.getSubscriberId();
        } catch (Exception e) {
            Log.e("8", e.getMessage());
            return "";
        }

    }

    /**
     * 9 获取分辨率
     *
     * @param context
     * @return
     */
    public static String getXY9(Context context) {
        try {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point point = new Point();
            display.getSize(point);
            int width = point.x;
            int height = point.y;
            return width + ":" + height;
        } catch (Exception e) {
            Log.e("9", e.getMessage());
            return "";
        }
    }

    /**
     * 10 获取开机时长
     */
    public static String getRunTime10() {
        return String.valueOf(SystemClock.elapsedRealtime());
    }

    /**
     * 11.获取海拔高度
     *
     * @param context
     * @return
     */
    public static String getAltitude11(Context context) {
        try {
            Location location = MSULocationUtils.getInstance(context).showLocation();
            if (location != null) {
                return String.valueOf(location.getAltitude());
            }
        } catch (Exception e) {
            Log.e("11", e.getMessage());
            return "";
        }
        return "";
    }

    /**
     * 14.获取经纬度  longitude 经度 latitude纬度
     *
     * @param context
     * @return
     */
    public static String getLocation14(Context context) {
        NumberFormat ddf1 = NumberFormat.getNumberInstance();
        ddf1.setMaximumFractionDigits(0);
        try {
            Location location = MSULocationUtils.getInstance(context).showLocation();
            if (location != null) {
                return ddf1.format(location.getLatitude()) + "," + ddf1.format(location.getLongitude());
            }
        } catch (Exception e) {
            Log.e("14", e.getMessage());
            return "";
        }
        return "";
    }

    /**
     * 12 系统日期和时间
     *
     * @return
     */
    public static String getTime12() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

    /**
     * 13 是否支持gps
     *
     * @param context
     * @return
     */
    public static String getSupportGPS13(Context context) {
        try {
            LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ? "true" : "false";
        } catch (Exception e) {
            Log.e("13", e.getMessage());
            return "";
        }

    }

    /**
     * 15 是否支持蓝牙
     *
     * @return
     */
    public static String getSupportBT15() {
        try {
            return BluetoothAdapter.getDefaultAdapter() == null ? "false" : "true";
        } catch (Exception e) {
            Log.e("15", e.getMessage());
            return "";
        }
    }

    /**
     * 16 是否连接了wifi
     *
     * @param context
     * @return
     */
    public static String isWiFiActive16(Context context) {
        try {
            WifiManager wifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);//得到wifi管理器对象
            return String.valueOf(wifimanager.isWifiEnabled());//返回wifi状态
        } catch (Exception e) {
            Log.e("16", e.getMessage());
            return "";
        }

    }

    /**
     * 17 是否支持陀螺仪
     *
     * @param context
     * @return
     */
    public static String isSupportTLY17(Context context) {
        try {
            SensorManager sm = (SensorManager) context.getSystemService(SENSOR_SERVICE);
            return sm == null ? "false" : "true";
        } catch (Exception e) {
            Log.e("17", e.getMessage());
            return "";
        }
    }

    /**
     * 18 是否是移动设备
     */
    public static String isPad18(Context context) {
        try {
            TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

            if (telephony != null) {
                if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
                    return "false";
                } else {
                    return "true";
                }
            } else {
                return "false";
            }
        } catch (Exception e) {
            Log.e("18", e.getMessage());
            return "";
        }
    }

    /**
     * 19 wifi的mac地址
     *
     * @param ctx
     * @return
     */
    public static String getWifiMac19(Context ctx) {
        try {
            WifiManager wifi = (WifiManager) ctx.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = null;
            if (wifi != null) {
                info = wifi.getConnectionInfo();
            } else {
                return "";
            }
            String str = info.getMacAddress();
            if (str == null) str = "";
            return str;
        } catch (Exception e) {
            Log.e("19", e.getMessage());
            return "";
        }
    }

    static int permissionCall = 0;

    /**
     * 20 获取手机IMEI号
     */
    public static String getIMEI20(Context context) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (permissionCall < 5) {
                        ((Activity) context).requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
                        permissionCall++;
                    }
                }
            }
            return telephonyManager.getDeviceId();
        } catch (Exception e) {
            Log.e("20", e.getMessage());
            return "";
        }

    }

    /**
     * 21.获取手机号
     *
     * @param context
     * @return
     */
    public static String getPhoneNum21(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    ((Activity)context).requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
//                }
            }

            String phoneNum = tm.getLine1Number();//手机号码
            return phoneNum.substring(3, phoneNum.length());
        } catch (Exception e) {
            Log.e("21", e.getMessage());
            return "";
        }
    }

    /**
     * 22.获取设备号
     *
     * @param context
     * @return
     */
    public static String getDeviceId22(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    ((Activity)context).requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
//                }
            }
            String deviceid = tm.getDeviceId();
            return deviceid;
        } catch (Exception e) {
            Log.e("22", e.getMessage());
            return "";
        }

    }

    /**
     * 23.获得IP地址，分为两种情况，一是wifi下，二是移动网络下，得到的ip地址是不一样的
     *
     * @param context
     * @return
     */
    public static String getIPAddress23(Context context) {
        try {
            return MSUHttpUtils.getNetIp();
        } catch (Exception e) {
            Log.e("23", e.getMessage());
            return "";
        }
    }


    /**
     * 24. 获取手机屏幕尺寸
     *
     * @return
     */
    public static String getRealScreenSize24(Context mContext) {
        try {
            NumberFormat ddf1 = NumberFormat.getNumberInstance();
            ddf1.setMaximumFractionDigits(1);
            float xdpi = mContext.getResources().getDisplayMetrics().xdpi;
            float ydpi = mContext.getResources().getDisplayMetrics().ydpi;
            int width = mContext.getResources().getDisplayMetrics().widthPixels;
            int height = mContext.getResources().getDisplayMetrics().heightPixels;

            float width2 = (width / xdpi) * (width / xdpi);
            float height2 = (height / ydpi) * (width / xdpi);
            return String.valueOf(ddf1.format(Math.sqrt(width2 + height2)));
        } catch (Exception e) {
            Log.e("24", e.getMessage());
        }
        return "";
    }

    /**
     * 25.获取密度和dpi
     *
     * @param context
     * @return
     */
    public static String getdensityDpi25(Context context) {
        try {
            DisplayMetrics mDisplayMetrics = context.getResources().getDisplayMetrics();
            int densityDpi = mDisplayMetrics.densityDpi;
            return String.valueOf(densityDpi);
        } catch (Exception e) {
            Log.e("25", e.getMessage());
            return "";
        }

    }


    /**
     * 26.获取sim序列号
     *
     * @param context
     * @return
     */

    public static String getSimNum26(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    ((Activity)context).requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
//                }
            }
            String simSerialNumber = tm.getSimSerialNumber();
            return simSerialNumber;
        } catch (Exception e) {
            Log.e("26", e.getMessage());
            return "";
        }
    }

    /**
     * 27.NFC信息
     */
    public static String getNFC27(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            boolean nfc = pm.hasSystemFeature(PackageManager.FEATURE_NFC);
            return nfc ? "true" : "false";
        } catch (Exception e) {
            Log.e("27", e.getMessage());
            return "";
        }

    }

    /**
     * 28 获得SD卡总大小
     *
     * @return
     */
    public static String getSDTotalSize28(Context context) {
        try {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            return Formatter.formatFileSize(context, blockSize * totalBlocks);
        } catch (Exception e) {
            Log.e("28", e.getMessage());
            return "";
        }

    }

    /**
     * 54 获得机身剩余内存
     *
     * @return
     */
    public static String getRomTotalSize54(Context context) {
        NumberFormat ddf1 = NumberFormat.getNumberInstance();
        ddf1.setMaximumFractionDigits(1);
        try {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
            activityManager.getMemoryInfo(mi);
            return ddf1.format((float) mi.availMem / (1024 * 1024 * 1024)) + "GB";
        } catch (Exception e) {
            Log.e("54", e.getMessage());
            return "";
        }
    }

    /**
     * 29.当前使用空间大小
     */
    public static String getRomUsedSize29(Context context) {
        try {
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            long availableBlocks = stat.getAvailableBlocks();
            long usedBlocks = totalBlocks - availableBlocks;
            return Formatter.formatFileSize(context, blockSize * usedBlocks);
        } catch (Exception e) {
            Log.e("29", e.getMessage());
            return "";
        }

    }

    /**
     * 30.剩余空间大小
     *
     * @return
     */
    public static String getRomAvailableSize30(Context context) {
        try {
            File path = Environment.getDataDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            return Formatter.formatFileSize(context, blockSize * availableBlocks);
        } catch (Exception e) {
            Log.e("30", e.getMessage());
            return "";
        }

    }


    /**
     * 31.获取蓝牙地址
     *
     * @return
     */
    public static String getBluetooth31() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Field field = null;
        try {
            field = BluetoothAdapter.class.getDeclaredField("mService");
            field.setAccessible(true);
            Object bluetoothManagerService = field.get(bluetoothAdapter);
            if (bluetoothManagerService == null) {
                return "";
            }
            Method method = bluetoothManagerService.getClass().getMethod("getAddress");
            if (method != null) {
                Object obj = method.invoke(bluetoothManagerService);
                if (obj != null) {
                    return obj.toString();
                }
            }
        } catch (Exception e) {
            Log.e("31", e.getMessage());
            return "";
        }
        return "";
    }


    /**
     * 32.获取内核版本信息
     *
     * @return
     */
    public static String getLinuxKernalInfoEx32() {
        String result = "";
        String line;
        String[] cmd = new String[]{"/system/bin/cat", "/proc/version"};
        String workdirectory = "/system/bin/";
        try {
            ProcessBuilder bulider = new ProcessBuilder(cmd);
            bulider.directory(new File(workdirectory));
            bulider.redirectErrorStream(true);
            Process process = bulider.start();
            InputStream in = process.getInputStream();
            InputStreamReader isrout = new InputStreamReader(in);
            BufferedReader brout = new BufferedReader(isrout, 8 * 1024);

            while ((line = brout.readLine()) != null) {
                result += line;
                // result += "\n";
            }
            in.close();

        } catch (Exception e) {
            Log.e("32", e.getMessage());
            return "";
        }
        return result;
    }


    /**
     * 33.获取CPU序列号 获取不到返回0000000000
     *
     * @return
     */
    public static String getCPUSerial33() {
        String str = "", strCPU = "", cpuAddress = "0000000000000000";
        try {
            //读取CPU信息
            Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            //查找CPU序列号
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    //查找到序列号所在行
                    if (str.indexOf("Serial") > -1) {
                        //提取序列号
                        strCPU = str.substring(str.indexOf(":") + 1,
                                str.length());
                        //去空格
                        cpuAddress = strCPU.trim();
                        break;
                    }
                } else {
                    //文件结尾
                    break;
                }
            }
        } catch (Exception e) {
            Log.e("33", e.getMessage());
            return "";
        }
        return cpuAddress;
    }


    /**
     * 34.获取CPU型号
     *
     * @return
     */
    public static String getCpuName34() {
        try {
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            String[] array = text.split(":\\s+", 2);
            for (int i = 0; i < array.length; i++) {
            }
            return array[1];
        } catch (Exception e) {
            Log.e("34", e.getMessage());
            return "";
        }
    }

    public static final int DEVICEINFO_UNKNOWN = 0;

    /**
     * 35.获取CPU核数  获取不到返回0
     *
     * @return
     */
    public static int getNumberOfCPUCores35() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
            // Gingerbread doesn't support giving a single application access to both cores, but a
            // handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core
            // chipset and Gingerbread; that can let an app in the background run without impacting
            // the foreground application. But for our purposes, it makes them single core.
            return 1;
        }
        int cores;
        try {
            cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;
        } catch (SecurityException e) {
            cores = DEVICEINFO_UNKNOWN;
        } catch (NullPointerException e) {
            cores = DEVICEINFO_UNKNOWN;
        }
        return cores;
    }

    private static final FileFilter CPU_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            String path = pathname.getName();
            //regex is slow, so checking char by char.
            if (path.startsWith("cpu")) {
                for (int i = 3; i < path.length(); i++) {
                    if (path.charAt(i) < '0' || path.charAt(i) > '9') {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
    };


    /**
     * 36.获取wifi热点列表 根据信号强度从强到弱进行排序
     *
     * @param context
     * @return
     */
    public static String getWifiListData36(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
            ArrayList<ScanResult> wifiList;                   //存放周围wifi热点对象的列表
            ArrayList<String> list = new ArrayList<>();                   //存放周围wifi热点对象的列表
            wifiList = sortByLevel((ArrayList<ScanResult>) wifiManager.getScanResults());
            for (int i = 0; i < wifiList.size(); i++) {
                list.add(wifiList.get(i).SSID);
            }
            return list.toString();
        } catch (Exception e) {
            Log.e("36", e.getMessage());
            return "";
        }

    }


    //将搜索到的wifi根据信号强度从强到弱进行排序
    public static ArrayList<ScanResult> sortByLevel(ArrayList<ScanResult> list) {
        for (int i = 0; i < list.size(); i++)
            for (int j = 1; j < list.size(); j++) {
                if (list.get(i).level < list.get(j).level)    //level属性即为强度
                {
                    ScanResult temp = null;
                    temp = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, temp);
                }
            }
        return list;
    }


    /**
     * 37.判断是否root
     *
     * @return
     */
    public static boolean isRoot37() {
        String binPath = "/system/bin/su";
        String xBinPath = "/system/xbin/su";

        try {
            if (new File(binPath).exists() && isCanExecute(binPath)) {
                return true;
            }
            if (new File(xBinPath).exists() && isCanExecute(xBinPath)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            Log.e("37", e.getMessage());
            return false;
        }
    }

    private static boolean isCanExecute(String filePath) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("ls -l " + filePath);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String str = in.readLine();
            if (str != null && str.length() >= 4) {
                char flag = str.charAt(3);
                if (flag == 's' || flag == 'x')
                    return true;
            }
        } catch (Exception e) {
            Log.e("ss", e.getMessage());
            return false;
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return false;
    }


    /**
     * 38.获取CPU当前频率 （单位KHZ）
     *
     * @return
     */
    public static String getCurCpuFreq38() {
        String result = "N/A";
        try {
            FileReader fr = new FileReader(
                    "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            result = text.trim();
        } catch (Exception e) {
            Log.e("38", e.getMessage());
            return "";
        }
        return result + "KHZ";
    }

    /**
     * 43.获取应用版本号 VersionCode
     *
     * @param context
     * @return
     */
    public static String getVersionCode43(Context context) {
        int versionCode = 0;
        try {
            versionCode = context
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(),
                            0).versionCode;
        } catch (PackageManager.NameNotFoundException ex) {
            versionCode = 0;
        }
        return String.valueOf(versionCode);
    }

    /**
     * 44.渠道对应AppKey
     *
     * @param context
     * @return
     */
    public static String getKey44(Context context) {
        return context.getSharedPreferences("sky", Context.MODE_PRIVATE).getString("key", "");
    }

    public static void setKey44(Context context, String key) {
        SharedPreferences.Editor edit = context.getSharedPreferences("sky", Context.MODE_PRIVATE).edit();
        edit.putString("key", key);
        edit.commit();
    }


    /**
     * 获取应用版本名 VersionName
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String name;
        try {
            name = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(),
                            0).versionName;
        } catch (PackageManager.NameNotFoundException ex) {
            name = "";
        }
        return name;
    }

    /**
     * 45.获取应用名
     *
     * @param context
     * @return
     */
    public static String getAppName45(Context context) {
        //包管理操作管理类
        PackageManager pm = context.getPackageManager();
        try {
            ApplicationInfo info = pm.getApplicationInfo(getAppProcessName46(context), 0);
            return info.loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return getAppProcessName46(context);
    }

    /**
     * 46.获取应用包名
     *
     * @param context
     * @return
     */
    public static String getAppProcessName46(Context context) {
        try {
            //当前应用pid
            int pid = android.os.Process.myPid();
            //任务管理类
            ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            //遍历所有应用
            List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo info : infos) {
                if (info.pid == pid)//得到当前应用
                    return info.processName;//返回包名
            }
            return "";
        } catch (Exception e) {
            Log.e("46", e.getMessage());
            return "";
        }

    }

    /**
     * 47
     *
     * @param context
     * @return String
     */
    public static String getUserID47(Context context) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            return sky.getString("userid", "");
        } catch (Exception e) {
            Log.e("47", e.getMessage());
            return "";
        }
    }

    public static void setUserID47(Context context, String id) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sky.edit();
            edit.putString("userid", id);
            edit.commit();
        } catch (Exception e) {
        }

    }

    /**
     * 47
     *
     * @param context
     * @return String
     */
    public static String getAppId64(Context context) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            return sky.getString("appid", "");
        } catch (Exception e) {
            Log.e("64", e.getMessage());
            return "";
        }
    }

    public static void setAppId64(Context context, String id) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sky.edit();
            edit.putString("appid", id);
            edit.commit();
        } catch (Exception e) {
        }

    }

    public static boolean isFirst(Context context) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            return sky.getBoolean("first", true);
        } catch (Exception e) {
            return true;
        }
    }

    public static void setFirst(Context context) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sky.edit();
            edit.putBoolean("first", false);
            edit.commit();
        } catch (Exception e) {
        }

    }

    /**
     * 51 获取当前CPU频率
     *
     * @return
     */
    public static String getCurCPU51() {
        int result = 0;
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
            br = new BufferedReader(fr);
            String text = br.readLine();
            result = Integer.parseInt(text.trim());
        } catch (Exception e) {
            Log.e("51", e.getMessage());
            return "";
        } finally {
            if (fr != null)
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return String.valueOf(result) + "KHZ";
    }


    /**
     * 55获取正在运行的APP列表
     */
    public static TreeSet<String> getAppInfos55(Context context) {
        try {
            TreeSet<String> objects = new TreeSet<>();
            final ActivityManager activityManager = (ActivityManager) context
                    .getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(100);

            Iterator<ActivityManager.RunningServiceInfo> l = services.iterator();
            while (l.hasNext()) {
                ActivityManager.RunningServiceInfo si = (ActivityManager.RunningServiceInfo) l.next();
                objects.add(si.process);
            }
            return objects;
        } catch (Exception e) {
            Log.e("55", e.getMessage());
            return new TreeSet<>();
        }

    }

    public static String getBatteryInfo(Context context) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            return sky.getString("batteryInfo", "");
        } catch (Exception e) {
        }
        return "";
    }

    public static void setBatteryInfo(Context context,String batteryInfo) {
        try {
            SharedPreferences sky = context.getSharedPreferences("sky", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sky.edit();
            edit.putString("batteryInfo", batteryInfo);
            edit.commit();
        } catch (Exception e) {
        }
    }
    public static Stack<String> viewStack = new Stack<>();

    public static ResultBean resultBean = new ResultBean();

    public static boolean isError = false;

}
